package com.css.dzj.dzjportal.modules.updown.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.css.dzj.dzjportal.common.util.http.HttpClientUtil;
import com.css.dzj.dzjportal.modules.updown.entity.CommAttachmentEntity;
import com.css.dzj.dzjportal.modules.updown.entity.QCommAttachmentEntity;
import com.css.dzj.dzjportal.modules.updown.mapper.CommAttachMapper;
import com.css.dzj.dzjportal.modules.updown.service.AttachService;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Properties;

@Service
public class AttachServiceImpl  implements AttachService {
    //注入JPAQueryFactory工厂
    @Autowired
    JPAQueryFactory jpaQueryFactory;
    @Autowired
    private CommAttachMapper commAttachMapper;
    @Autowired
    private HttpServletResponse response;

    @Override
    public List<CommAttachmentEntity> queryAll(String id) {
        //id为tableUuid
        QCommAttachmentEntity q = QCommAttachmentEntity.commAttachmentEntity;
        com.querydsl.core.types.Predicate predicate = q.isNotNull().or(q.isNull());
        //predicate = ExpressionUtils.and(predicate, q.delFlag.eq(Constant.NO_DELETE));
        predicate = ExpressionUtils.and(predicate, q.tableUuid.eq(id));
        List<CommAttachmentEntity> attachmentEntities = jpaQueryFactory
                .selectFrom(q)
                .where(predicate)
                .orderBy(
                        // 根据创建日期，降序排序
                        q.uploadtime.desc()
                ).fetch();
        return attachmentEntities;
    }

    @Override
    public String save(MultipartFile file, String id)  throws IOException {
        String fileName = file.getOriginalFilename();
        //处理上传，获取系统类型
        Properties props = System.getProperties();
        String property = props.getProperty("os.name");
        String realPath ;
        if(property.indexOf("Windows")==0){
            File view=new File("D:/view/");
            if(!view.exists()){
                view.mkdirs();
            }
            realPath= "D:/view/";//windows系统
        }else {
            File view=new File("/view/");
            if(!view.exists()){
                view.mkdirs();
            }
            realPath= "/view/";//其他系统
        }
        file.getOriginalFilename();
        //获取格式
        String extension = FilenameUtils.getExtension(fileName);
        // String newFileName = appear.getUuid().replace("-","")+"."+extension;
        //获取时间戳更换名称
        String newFileName = System.currentTimeMillis()+"."+extension;
        file.transferTo(new File(realPath,newFileName));
        CommAttachmentEntity item = new CommAttachmentEntity();
        item.setFileurl(realPath);
        item.setTableName(newFileName);
        item.setFilename(fileName);
        item.setFileext(extension);
        item.setTableUuid(id);
        Integer originals = (Integer.parseInt(String.valueOf(file.getSize())))/1024;
        String size = String.valueOf(file.getSize());
        if(originals<0||originals==0){
            item.setFilesize(size+"B");
        }else {
            int a = Integer.parseInt(size);
            DecimalFormat df = new DecimalFormat("0.00");//格式化小数
            if (originals < 1024 ) {
                size = df.format((float) a / 1024);//返回的是String类型
                item.setFilesize(size+"KB");
            } else if (originals < 1048576 ) {
                size = df.format((float) a / 1048576);//返回的是String类型
                item.setFilesize(size+"MB");
            } else {
                size = df.format((float) a / 1073741824);//返回的是String类型
                item.setFilesize(size+"GB");
            }
        }
        commAttachMapper.save(item);
        return "ok";
    }

    @Override
    public String download(String id) throws IOException {
        if(id !=null){
            //该ID为UUID
            CommAttachmentEntity commAttach = commAttachMapper.getOne(id);
            //获取文件名称
            String fileName = commAttach.getFilename();
            System.out.println("下载的文件名: "+fileName);
            //设置文件路径
            //String realPath = DigestUtils.md5DigestAsHex((commAttach.getFileurl()+commAttach.getMd5Uuid()).getBytes());
            String realPath = commAttach.getFileurl();
            //路径名称+服务器中存储的时间戳名称
            File file = new File(realPath,commAttach.getTableName());
            if(file.exists()){
                //设置强制下载不打开
                System.out.println();
                response.setContentType("application/force-download");
                //文件下载后，
                response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8"));
                //response.setHeader("content-disposition","attachment;fileName="+ fileName);
                //response.addHeader("Content-Disposition","attachment:fileName="+fileName);
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    System.out.println();
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("success");
                    os.close();
                    return "ok";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "error";
    }

    @Override
    public String del(String id) {
        String resultInfo ;
        CommAttachmentEntity commAttach = commAttachMapper.getOne(id);
        String url = commAttach.getFileurl();
        File file = new File(url,commAttach.getTableName());
        if(file.exists()){
            if(file.delete()){
                System.out.println(id);
                commAttachMapper.deleteById(id);
                resultInfo = "ok";
            }else{
                resultInfo = "error";
            }
        }else{
            resultInfo = "文件不存在！";
        }
        return  resultInfo;
    }

    /**
     * 下载公开公告
     * @param commAttach
     * @return
     * @throws IOException
     */
    @Override
    @Transactional
    public String downloadPublic(CommAttachmentEntity commAttach) throws IOException {
        if(commAttach !=null){
            //获取文件名称
            String fileName = commAttach.getFilename();
            System.out.println("下载的文件名: "+fileName);
            //设置文件路径
            //String realPath = DigestUtils.md5DigestAsHex((commAttach.getFileurl()+commAttach.getMd5Uuid()).getBytes());
            String realPath = commAttach.getFileurl();
            //路径名称+服务器中存储的时间戳名称
            File file = new File(realPath,commAttach.getTableName());
            if(file.exists()){
                //设置强制下载不打开
                System.out.println();
                response.setContentType("application/force-download");
                //文件下载后，
                response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8"));
                //response.setHeader("content-disposition","attachment;fileName="+ fileName);
                //response.addHeader("Content-Disposition","attachment:fileName="+fileName);
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    System.out.println();
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("success");
                    os.close();
                    return "ok";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "error";
    }

    /**
     * 上传投诉举报附件
     * @param file
     * @param id
     * @param wgrRestUrl
     * @return
     * @throws IOException
     */
    @Override
    public String saveTsjbfj(MultipartFile file, String id,String wgrRestUrl)  throws IOException {
        String fileName = file.getOriginalFilename();
        //处理上传，获取系统类型
        Properties props = System.getProperties();
        String property = props.getProperty("os.name");
        String realPath ;
        if(property.indexOf("Windows")==0){
            File view=new File("D:/view/");
            if(!view.exists()){
                view.mkdirs();
            }
            realPath= "D:/view/";//windows系统
        }else {
            File view=new File("/view/");
            if(!view.exists()){
                view.mkdirs();
            }
            realPath= "/view/";//其他系统
        }
        file.getOriginalFilename();
        //获取格式
        String extension = FilenameUtils.getExtension(fileName);
        // String newFileName = appear.getUuid().replace("-","")+"."+extension;
        //获取时间戳更换名称
        String newFileName = System.currentTimeMillis()+"."+extension;
        file.transferTo(new File(realPath,newFileName));
        CommAttachmentEntity item = new CommAttachmentEntity();
        item.setFileurl(realPath);
        item.setTableName(newFileName);
        item.setFilename(fileName);
        item.setFileext(extension);
        item.setTableUuid(id);
        Integer originals = (Integer.parseInt(String.valueOf(file.getSize())))/1024;
        String size = String.valueOf(file.getSize());
        if(originals<0){
            item.setFilesize(size+"B");
        }else {
            int a = Integer.parseInt(size);
            DecimalFormat df = new DecimalFormat("0.00");//格式化小数
            if (originals < 1024 ) {
                size = df.format((float) a / 1024);//返回的是String类型
                item.setFilesize(size+"KB");
            } else if (originals < 1048576 ) {
                size = df.format((float) a / 1048576);//返回的是String类型
                item.setFilesize(size+"MB");
            } else {
                size = df.format((float) a / 1073741824);//返回的是String类型
                item.setFilesize(size+"GB");
            }
        }
        String itemVO = JSON.toJSONString(item);
        String msg= HttpClientUtil.doPostJson(wgrRestUrl + "/ud/saveAttachVO",itemVO);
        JSONObject jsonObject=(JSONObject)JSON.parse(msg);
        if(jsonObject.get("code").equals(200)){
            return "200";
        }else {
            return null;
        }
    }
}
